package com.hula.onion.book.server.spider.platforms.mintoujinfu;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description:链链金融
 * Create Date:2018/1/30 19:33
 *
 * @author liangbing
 * @version 1.0
 */
@Component("minTouJinFuSpider")
public class MinTouJinFuSpider extends SpiderCommon {

    /**
     * 登录页面URL
     */
    private static final String LOGIN_PAGE_URL = "https://www.100lending.com/user/login";

    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.100lending.com/user/login";

    /**
     * 验证码URL
     */
    private static final String CAPTCHA_URL = "https://www.100lending.com/user/captcha.login";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.100lending.com/my/";

    @Autowired
    private MinTouJinFuSpiderHelper spiderHelper;

    /**
     * 执行爬取操作
     */
    @Override
    public CommonResponse execute() {
        //1. 从缓存中获取cookie，设置到cookie store中
        CookieUtils.setCookie(loginForm.getPlatformId(), loginForm.getUserId(), getHttpContext().getCookieStore());

        //模拟登陆
        String loginStr = HttpUtils.post(LOGIN_URL,
                spiderHelper.installRequestParams(loginForm),
                getHttpContext());
        if (StringUtils.isEmpty(loginStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        logger.info("[MinTouJinFuSpider] Http response result:{}", loginStr);
        String status = JSONObject.parseObject(loginStr).getString("status");
        System.out.println(loginStr);
        //登陆成功
        if ("1".equals(status)) {
            // 爬取数据
            String html = HttpUtils.get(GET_ACCOUNT_INFO_URL, getHttpContext());
            return spiderHelper.parseAccountBalance(html);
        } else if ("1005".equals(status)) {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        } else if ("1001".equals(status)) {
            return new CommonResponse(ResponseStatusEnum.VERIFY_CODE_FAIL);
        }
        return new CommonResponse(ResponseStatusEnum.FAIL);
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL + "?" + System.currentTimeMillis();
    }

    @Override
    public String getLoginPageURL() {
        return LOGIN_PAGE_URL;
    }

}

